package bar.dark.lee.alarm.sound;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import bar.dark.lee.alarm.R;
import bar.dark.lee.alarm.SuperActivity;

public class SoundActivity extends SuperActivity
{
	public static final int REQUEST_SOUND_FOLDER = 0;
	
	public static final String SOUND_FILE_DATA = "sound_file_data";
	public static final String SELECT_DATA = "select_data";
	
	private ListView listView;
	private View resultView;
	
	private Button saveButton;
	private Button addButton;
	private Button cancelButton;
	
	private ArrayList<SoundData> list = null;
	private MediaPlayer mp;
	private AudioManager am;
	
	private int maxVolum;
	private int streamType = AudioManager.STREAM_RING;
	
	private SoundData selectData = null;
	
	private String filePath = "";
	private String fileName = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.sound_activity);
		
		setTitle(getResources().getString(R.string.sound_title));
		
		setFindView();
		setClickListener();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		new ShowDialog().execute(0);
	}
	
	@Override
	public void setFindView()
	{
		listView = (ListView) findViewById(R.id.soundListView);
		saveButton = (Button) findViewById(R.id.soundSaveButton);
		cancelButton = (Button) findViewById(R.id.soundCancelButton);
		addButton = (Button) findViewById(R.id.soundAddButton);
		
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
	}

	@Override
	public void setDataSetting()
	{
		fileName = getIntent().getStringExtra(SELECT_DATA);
		list = query.getAlarmSound(superContext);
		mp = new MediaPlayer();
		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		maxVolum = am.getStreamMaxVolume(streamType);
		am.setStreamVolume(streamType, maxVolum, AudioManager.STREAM_RING);
	}

	@Override
	public void setClickListener()
	{
		saveButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.putExtra(SOUND_FILE_DATA, selectData);
				setResult(Activity.RESULT_OK, intent);
				
				if (mp.isPlaying())
				{
					mp.stop();
					mp.reset();
				}
				
				finish();
			}
		});
		
		addButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (mp.isPlaying())
				{
					mp.stop();
					mp.reset();
				}
				
				Intent intent = new Intent(superContext, SoundFolderActivity.class);
				startActivityForResult(intent, REQUEST_SOUND_FOLDER);
			}
		});
		
		cancelButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				onBackPressed();
			}
		});
	}
	
	@Override
	public void onBackPressed()
	{
		super.onBackPressed();
		if (mp.isPlaying())
		{
			mp.stop();
			mp.reset();
		}
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3)
		{
			SoundData data = list.get(pos); 
			
			for (int i = 0; i < arg0.getChildCount(); i++)
			{
				ViewGroup vg = (ViewGroup) arg0.getChildAt(i);
				ViewGroup vgc = (ViewGroup) vg.getChildAt(0);
				RadioButton r = (RadioButton) vgc.getChildAt(1);
				r.setChecked(false);
			}
			
			RadioButton rb = (RadioButton) arg1.findViewById(R.id.listItemRadio);
			rb.setChecked(true);
			
			mp.setAudioStreamType(streamType);
			
			if (mp.isPlaying())
			{
				if (filePath.equals(data.getFileLocation()))
				{
					mp.pause();
				}
				else
				{
					mp.stop();
					mp.reset();
					
					try
					{
						mp.setDataSource(data.getFileLocation());
						filePath = data.getFileLocation();
						selectData = data;
						mp.prepare();
					} catch (Exception e)
					{
						e.printStackTrace();
					}
					
					mp.start();
				}
			}
			else
			{
				if (filePath.equals(data.getFileLocation()))
				{
					mp.start();
				}
				else
				{
					try
					{
						mp.reset();
						mp.setDataSource(data.getFileLocation());
						filePath = data.getFileLocation();
						selectData = data;
						mp.prepare();
					} catch (Exception e)
					{
						e.printStackTrace();
					}
					
					mp.start();
				}
			}
		}
	};
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(superContext);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0)
			{
				setDataSetting();
				return 0;
			}

			return -1;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == 0)
			{
				if (listView.getFooterViewsCount() > 0)
				{
					listView.removeFooterView(resultView);
				}
				
				if (list.size() < 1)
				{
					listView.addFooterView(resultView);
					listView.setFooterDividersEnabled(false);
				}
				else
				{
					listView.setOnItemClickListener(onItemClickListener);
					listView.setDividerHeight(1);
				}
				
				SoundAdapter adapter = new SoundAdapter(superContext, R.layout.list_item_sound, list);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	private class SoundAdapter extends ArrayAdapter<SoundData>
	{
		private ArrayList<SoundData> list;
		
		public SoundAdapter(Context context, int textViewResourceId,
				List<SoundData> objects)
		{
			super(context, textViewResourceId, objects);
			this.list = (ArrayList<SoundData>) objects;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				v = getLayoutInflater().inflate(R.layout.list_item_sound, null);
			}
			
			SoundData data = list.get(position);
			
			TextView tv = (TextView) v.findViewById(R.id.listItemTextView);
			RadioButton rb = (RadioButton) v.findViewById(R.id.listItemRadio);
			
			tv.setText(data.getFileName());
			
			if (data.getFileName().equals(fileName))
			{
				rb.setChecked(true);
			}
			else
			{
				rb.setChecked(false);
			}
			
			return v;
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
